import axios from 'axios'
import global from './global'

// axios.defaults.baseURL = '/api'
axios.defaults.timeout = 5000;                        //响应时间
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';        //配置请求头

let utils = {}
utils.install = function (Vue, options) {
	Vue.prototype.text = async function(url, postData = {}, method='get') {
		axios.defaults.headers['token'] = global.token;        //配置请求头
		// axios.defaults.withCredentials=true
		let data = ""
		let code = ""
		let msg = ""
		
		

		try {
			let temp = await axios({
				method: method,//指定请求方式
				url: url,
				data: postData
			})

			data = temp.data.data
			code = temp.data.code
			msg = temp.data.msg

		} catch (error) {
			data = error;
			code = 500
		}
		
		if(code === 50002){
			this.$message.error('登陆状态异常');
			this.$logOut()
			this.$router.push("login")
		}
		
		return {data,code,msg};

	};
	Vue.prototype.$dateFormat = function(date) {
		// 
		let fmt = "YYYY-mm-dd HH:MM"
		  let ret="";
		  date=new Date(date);
		  const opt = {
			'Y+': date.getFullYear().toString(), // 年
			'm+': (date.getMonth() + 1).toString(), // 月
			'd+': date.getDate().toString(), // 日
			'H+': date.getHours().toString(), // 时
			'M+': date.getMinutes().toString(), // 分
			'S+': date.getSeconds().toString() // 秒
			// 有其他格式化字符需求可以继续添加，必须转化成字符串
		  }
		  for (let k in opt) {
			ret = new RegExp('(' + k + ')').exec(fmt)
			if (ret) {
			  fmt = fmt.replace(
				ret[1],
				ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, '0')
			  )
			}
		  }
		  return fmt
	};
	Vue.prototype.$logOut = function(date) {
		 this.text(this.$api.logOut);
		this.$GLOBAL.isLogin = false
		this.$GLOBAL.avatar = "http://192.168.10.164:8181/download?name=avatar/0.png"
		this.$GLOBAL.token = ""
		this.$GLOBAL.isInsider = false
		this.$GLOBAL.isAdmin = false
		sessionStorage.setItem("isInsider", false);	
		sessionStorage.setItem("isLogin", false)
		sessionStorage.setItem("isAdmin", false)
	};
};

export default utils